#include "thread_container.h"

void network::thread_container::add(network::thread_container::thrd_ptr p)
{
	boost::mutex::scoped_lock l(_mon);
	_list.push_back(p);
}

void network::thread_container::remove(network::thread_container::thrd_ptr p)
{
	boost::mutex::scoped_lock l(_mon);
	_list.remove(p);
}

network::thread_container::thrd_ptr network::thread_container::find(
	const network::worker_thread *thrd)
{
	boost::mutex::scoped_lock l(_mon);
	typedef list<network::thread_container::thrd_ptr>::iterator it;
	for(it i = _list.begin(); i != _list.end(); ++i) {
		if(i->get() == thrd) {
			return *i;
		}
	}
}

void network::thread_container::join_all()
{
	boost::mutex::scoped_lock l(_mon);
	typedef list<network::thread_container::thrd_ptr>::iterator it;
	for(it i = _list.begin(); i != _list.end(); ++i) {
		(*i)->join();
	}
}

void network::thread_container::interrupt()
{
	boost::mutex::scoped_lock l(_mon);
	typedef list<network::thread_container::thrd_ptr>::iterator it;
	for(it i = _list.begin(); i != _list.end(); ++i) {
		(*i)->interrupt();
	}
}

void network::thread_container::start_threads()
{
	boost::mutex::scoped_lock l(_mon);
	typedef list<network::thread_container::thrd_ptr>::iterator it;
	for(it i = _list.begin(); i != _list.end(); ++i) {
		(*i)->start_thread();
	}
}

void network::thread_container::notify(const network::notifier *n)
{
	const network::worker_thread *t = 
		dynamic_cast<const network::receiver *>(n);
	if(!t) {
		return;
	}
	thrd_ptr ptr = find(t);
	remove(ptr);
}

